/****************************************************************************
 Copyright (c) 2015-2017 Chukong Technologies Inc.

 http://www.cocos2d-x.org

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ****************************************************************************/
package org.cocos2dx.cpp;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.mchsdk.open.AnnounceTimeCallBack;
import com.mchsdk.open.GPExitResult;
import com.mchsdk.open.GPUserResult;
import com.mchsdk.open.IGPExitObsv;
import com.mchsdk.open.IGPUserObsv;
import com.mchsdk.open.MCApiConstants;
import com.mchsdk.open.MCApiFactory;
import com.mchsdk.open.OrderInfo;
import com.mchsdk.open.PayCallback;

import org.cocos2dx.lib.Cocos2dxActivity;

public class AppActivity extends Cocos2dxActivity {

    private static AppActivity mActivity;
    private static final String TAG = "AppActivity";

    private static final int GET_INIT_SUCCESS = 0x1;
    private static final int GET_STARTLOGIN_SUCCESS = 0x2;
    private static final int GET_RECHARGE_SUCCESS = 0x3;
    private static final int GET_LOGOUT_SUCEESS = 0x4;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_INIT_SUCCESS:
                    SdkDoMain sdkDoMain = (SdkDoMain) msg.obj;
                    if (sdkDoMain == null) {
                        Log.e(TAG, "sdkDoMain is null");
                        return;
                    }
                    MCApiFactory.getMCApi().setParams(sdkDoMain.getPromoteId(), // 渠道id
                            sdkDoMain.getPromoteAccount(),// 渠道名称
                            sdkDoMain.getGameId(), // 游戏id(编号)
                            sdkDoMain.getGameName(),// 游戏名称
                            sdkDoMain.getGameAppid(), // 游戏appid
                            sdkDoMain.getPaysdk_signkey(),// 访问秘钥： (SDK访问服务器时的加密key)
                            sdkDoMain.getPaysdk_address());// 联运SDK服务器地址

//                    // 2.初始化方法
                    MCApiFactory.getMCApi().init(AppActivity.this, true);
//
//                    /** 3. 个人中心里面点击退出登录执行的退出回调接口,根据实际需要选择 **/
                    MCApiFactory.getMCApi().initExitFromPersonInfoParams(mExitObsvPerson);
//
                    showToast("初始化成功");
                    break;
                case GET_STARTLOGIN_SUCCESS:
                    MCApiFactory.getMCApi().startlogin(AppActivity.this, new IGPUserObsv() {
                        @Override
                        public void onFinish(GPUserResult result) {

                            switch (result.getmErrCode()) {
                                case GPUserResult.USER_RESULT_LOGIN_FAIL:
                                    Toast.makeText(AppActivity.this, "登录失败", Toast.LENGTH_LONG)
                                            .show();
                                    Log.w(TAG, "登录失败");
                                    returnLoginResult("", "");
                                    break;
                                case GPUserResult.USER_RESULT_LOGIN_SUCC:
                                    Toast.makeText(AppActivity.this, "登录成功", Toast.LENGTH_LONG)
                                            .show();
                                    MCApiFactory.getMCApi().startFloating(AppActivity.this);
                                    String uid = result.getAccountNo();// 登录用户id
                                    String token = result.getToken();
                                    result.getAccount();
                                    Log.w(TAG, "userid = " + uid + "， token = " + token);
                                    returnLoginResult(uid, token);
                                    // 将这里返回的用户id和token返回给cp服务器，cp服务器发送给sdk服务器验证登录结果
                                    // 以下代码模拟服cp服务器访问sdk服务器登录验证,这个验证需要写在cp服务器
//                        TestProcess process = new TestProcess();
//                        process.token = token;
//                        process.user_id = uid;
//                        process.post(verifyLoginhandler);
//                    //设置防沉迷回调
                                    MCApiFactory.getMCApi().initAnnounceTimeCallBack(announceTimeCallBack);
                                    break;
                            }
                        }
                    });
                    break;

                case GET_RECHARGE_SUCCESS:
                    OrderInfo order = (OrderInfo) msg.obj;
                    MCApiFactory.getMCApi().pay(AppActivity.this, order, payCallback);
                    break;

                case GET_LOGOUT_SUCEESS:
                    MCApiFactory.getMCApi().loginout(AppActivity.this);
                    break;
            }
        }
    };

    /**
     * 支付结果回调
     */
    private PayCallback payCallback = new PayCallback() {
        @Override
        public void callback(String errorcode) {
            if (TextUtils.isEmpty(errorcode)) {
                return;
            }
            Log.w(TAG, errorcode);
            returnPayResult(errorcode);
            if ("0".equals(errorcode)) {
                Toast.makeText(AppActivity.this, "支付成功", Toast.LENGTH_LONG).show();
            } else if ("1".equals(errorcode)) {
                //可以当做支付成功
                Toast.makeText(AppActivity.this, "支付宝支付正在确认", Toast.LENGTH_LONG).show();
            } else if ("2".equals(errorcode)) {
                Toast.makeText(AppActivity.this, "支付宝支付未获取到支付结果", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(AppActivity.this, "支付失败", Toast.LENGTH_LONG).show();
            }
        }
    };


    /**
     * 支付结果通知,登录结果通知,防沉迷回调
     * MyGame  是编译c＋＋后生成的链接库名，可以在android.mk中看到这样一句话
     * LOCAL_MODULE_FILENAME :=libMyGame，lib后面的名字就是链接库名。
     * @return
     */
    static {
        System.loadLibrary("MyGame");
    }

    public static native void returnPayResult(String payResult);   // 这里必须是native函数，因为要链接c＋＋的实现

    public static native void returnLoginResult(String userid, String token);

    public static native void returnAntiAddictionResult(String antiAddictionResule);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
    }

    public void init(String promoteId, String promoteAccount,
                     String gameId, String gameName, String gameAppid, String paysdk_signkey, String paysdk_address) {
        // 第一个参数和第二个参数：渠道id和渠道名称，一般联运不会特殊要求，这里填写固定值“0”和“自然注册”即可
        //第三、第四、第五个参数分别为： 游戏id、游戏名称、游戏appid，一般联运会要求填写对应游戏的真实参数以方便在联运后台区分对接是否成功
        // 第六、第七个参数：访问秘钥和联运SDK服务器地址联运提供

        SdkDoMain sdkDoMain = new SdkDoMain(promoteId, promoteAccount, gameId, gameName, gameAppid, paysdk_signkey, paysdk_address);
        Message msg = new Message();
        msg.what = GET_INIT_SUCCESS;
        msg.obj = sdkDoMain;
        mHandler.sendMessage(msg);
    }

    /**
     * 注销
     */
    public void logout() {
        Message msg = new Message();
        msg.what = GET_LOGOUT_SUCEESS;
        mHandler.sendMessage(msg);
    }

    /**
     * 个人中心退出方法回调，根据实际需要进行操作
     */
    private IGPExitObsv mExitObsvPerson = new IGPExitObsv() {

        @Override
        public void onExitFinish(GPExitResult gpExitResult) {
            switch (gpExitResult.mResultCode) {
                case GPExitResult.GPSDKResultCodeOfPersonInfo:
                    Log.i(TAG, "退出回调:执行SDK个人中心退出方法");
                    break;
                default:
                    break;
            }
        }
    };

    public static Object getActivity() {
        return mActivity;
    }

    public void startLogin() {
        Log.i(TAG, "调用登录方法成功: ");

        Message msg = new Message();
        msg.what = GET_STARTLOGIN_SUCCESS;
        mHandler.sendMessage(msg);

    }

    /**
     * 防沉迷时间回掉
     */
    private AnnounceTimeCallBack announceTimeCallBack = new AnnounceTimeCallBack() {
        @Override
        public void callback(String result) {
            Log.i(TAG, "result: " + result);
            returnAntiAddictionResult(result);
            if (TextUtils.isEmpty(result)) {
                return;
            }
            if ("1".equals(result)) {
                //第一次到时通知
                Log.i(TAG, "第一次到时通知");
            }
            if ("2".equals(result)) {
                //第二次到时通知,玩家进入疲劳游戏时间
                Log.i(TAG, "第二次到时通知");
            }
            if ("3".equals(result)) {
                Log.e(TAG, "时间到，停止计时。");
            }

        }
    };


    private void showToast(String str) {
        Toast.makeText(AppActivity.this, str, Toast.LENGTH_LONG).show();
    }


    /**
     * 游戏从后台开始，开始计时
     */
    @Override
    protected void onResume() {
        super.onResume();
        //操作悬浮窗
        MCApiFactory.getMCApi().startFloating(AppActivity.this);
        MCApiFactory.getMCApi().onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        MCApiFactory.getMCApi().stopFloating(AppActivity.this);
    }

    /**
     * 游戏进入后台或退出游戏时，请求下线（下线通知）
     */
    @Override
    protected void onStop() {
        super.onStop();
        MCApiFactory.getMCApi().onStop(AppActivity.this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MCApiFactory.getMCApi().stopFloating(AppActivity.this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            MCApiFactory.getMCApi().exitDialog(AppActivity.this, mExitObsv);
        }
        return super.onKeyDown(keyCode, event);
    }


    /*
     * 1.如果你APP设置的targetSdkVersion大于和等于23，需要在登录Activity添加如下回调，用于通知权限申请结果
     * 2.如果不使用第三方登录可以不用配置
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == MCApiConstants.MCH_WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(AppActivity.this, "请尽情玩耍吧~", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(AppActivity.this, "限制后，无法使用第三发登录！", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 退出界面回调接口
     */
    private IGPExitObsv mExitObsv = new IGPExitObsv() {
        @Override
        public void onExitFinish(GPExitResult exitResult) {
            switch (exitResult.mResultCode) {
                case GPExitResult.GPSDKExitResultCodeError:
                    Log.e(TAG, "退出回调:调用退出弹框失败");
                    break;
                case GPExitResult.GPSDKExitResultCodeExitGame:
                    Log.e(TAG, "退出回调:退出方法回调");
                    // 关闭悬浮窗
                    MCApiFactory.getMCApi().stopFloating(AppActivity.this);
                    // 下面是退出逻辑,解决退出之后微信还在的问题
                    Intent MyIntent = new Intent(Intent.ACTION_MAIN);
                    MyIntent.addCategory(Intent.CATEGORY_HOME);
                    startActivity(MyIntent);
//                    // 你自己的退出逻辑，退出程序
//                    finish();
//                    System.exit(0);
                    break;
            }
        }
    };

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }

    public void pay(String productName, String productDesc, int amount, String extendInfo) {

        OrderInfo order = new OrderInfo();
        order.setProductName(productName);// 物品名称
        order.setProductDesc(productDesc); // 物品描述
        order.setAmount(amount);//商品价格（单位分）
        order.setExtendInfo(extendInfo); // 用于确认交易给玩家发送商品
//				order.setGameServerId("12");//游戏区服ID

        Message msg = new Message();
        msg.what = GET_RECHARGE_SUCCESS;
        msg.obj = order;
        mHandler.sendMessage(msg);
    }


}
